package com.xywy.bloodandroid.act;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.xywy.bloodandroid.R;
import com.xywy.bloodandroid.adapter.DoctorOrderAdapter;
import com.xywy.bloodandroid.base.BaseActivity;
import com.xywy.bloodandroid.bean.DoctorOrderSchedule;
import com.xywy.bloodandroid.bean.HotDoctorInfo;
import com.xywy.bloodandroid.bean.OrderDoctorFlag;
import com.xywy.bloodandroid.bean.User;
import com.xywy.bloodandroid.util.Constants;
import com.xywy.bloodandroid.util.DateUtil;
import com.xywy.bloodandroid.util.ImageLoader;
import com.xywy.bloodandroid.util.ImageLoader.ImageCallback;
import com.xywy.bloodandroid.util.JsonUtil;
import com.xywy.bloodandroid.util.UIUtil;
import com.xywy.bloodandroid.vollery.GetRequest;
import com.xywy.bloodandroid.vollery.OnVolleyResponseListener;

public class OrderDoctorAct extends BaseActivity {

	private RelativeLayout left_img;
	private TextView middle_title;
	 private GridView mygridview;

	private String name1;
	private String url1;
	private String hospital1;
	private String doctor_appellation1;
	private String recollections1;
	private String doctor_honor1;
	private String doctor_areas1;
	private String expertid;
	private String doc_id;
	private TextView doctor_name;
	private ImageView doctor_img;
	private TextView hosptail_name;
	private TextView doctor_appellation;
	private TextView recollections;
	private TextView doctor_honor;
	private TextView doctor_areas;

	private List<DoctorOrderSchedule> tempData = new ArrayList<DoctorOrderSchedule>();//获取数据的list
	
	List<OrderDoctorFlag> list=new ArrayList<OrderDoctorFlag>();//重组数据的集合

	private ImageLoader loader = new ImageLoader();
	private String id;
	 private DoctorOrderAdapter adapter;

	private HashMap<Integer, String> map = null;

	protected static final int DOCTORSCHEDULSUCESS = -99;

	@Override
	protected void initView(Bundle savedInstanceState) {
		setContentView(R.layout.act_order_doctor);
		left_img = (RelativeLayout) findViewById(R.id.left_img);
		middle_title = (TextView) findViewById(R.id.middle_title);
		middle_title.setText(R.string._order_doctor);

		doctor_name = (TextView) findViewById(R.id.doctor_name);
		doctor_img = (ImageView) findViewById(R.id.doctor_img);
		hosptail_name = (TextView) findViewById(R.id.hosptail_name);
		doctor_appellation = (TextView) findViewById(R.id.doctor_appellation11);
		recollections = (TextView) findViewById(R.id.recollections111);
		doctor_honor = (TextView) findViewById(R.id.doctor_honor);
		doctor_areas = (TextView) findViewById(R.id.doctor_areas);
		
		mygridview=(GridView)findViewById(R.id.mygridview);
   
		 tempData=new ArrayList<DoctorOrderSchedule>();
//		 mygridview = (GridView) findViewById(R.id.mygridview);
//		 adapter = new DoctorOrderAdapter(context, list);
//		 mygridview.setAdapter(adapter);

	}

	@Override
	protected void initListener() {
		left_img.setOnClickListener(this);
	}

	@Override
	protected void initData() {
		Intent intent = getIntent();
		HotDoctorInfo doctor = (HotDoctorInfo) intent
				.getSerializableExtra("HotDoctorInfo");
		name1 = doctor.getName();
		doc_id = doctor.getDocument_id();
		System.out.println("|||||"+doc_id);
		url1 = doctor.getApp_image();
		hospital1 = doctor.getHospital();
		doctor_appellation1 = doctor.getTitle();
		recollections1 = doctor.getDepart();
		doctor_honor1 = doctor.getTeach();
		doctor_areas1 = doctor.getGoodat();
		expertid = doctor.getExpert_id();
		
		id = doctor.getDocument_id();

		Drawable cachedImage = loader.loadDrawable(url1, doctor_img,
				new ImageCallback() {
					@Override
					public void imageLoaded(Drawable imageDrawable,
							ImageView imageView, String imageUrl) {
						if (imageView != null && imageDrawable != null) {
							imageView.setBackgroundDrawable(imageDrawable);
						}
					}
				});
		if (cachedImage == null) {
			doctor_img.setBackgroundResource(R.drawable.head);
		} else {
			doctor_img.setBackgroundDrawable(cachedImage);
		}

		doctor_name.setText(name1);
		hosptail_name.setText(hospital1);
		doctor_appellation.setText(doctor_appellation1);
		recollections.setText(recollections1);
		doctor_honor.setText(doctor_honor1);
		doctor_areas.setText(doctor_areas1);

		getDoctorDetail(expertid);

	}

	/**
	 * 获取 医生的详情 包含是否可以预约等信息
	 */
	private void getDoctorDetail(String expertid) {

		final Message msg = Message.obtain();
		GetRequest<String> getRequest = new GetRequest<String>(
				Constants.getUrl("zhuanjia", "DoctorDetail")
						+ "&pagesize=10&pagenum=1" + "&expertid=" + expertid
						+ "&id=" + id, String.class,
				new OnVolleyResponseListener<String>() {

					@Override
					public void onError(VolleyError volleyError) {
						UIUtil.DissDialog(context, waittingDialog);
						UIUtil.showToast(context,
								context.getString(R.string.network_slow));
					}

					@Override
					public void onSuccess(String response) {
						UIUtil.DissDialog(context, waittingDialog);

						try {
							JSONObject object = new JSONObject(response);
							int satate = object.optInt("code");
							String Msg = object.optString("msg");
							if (satate == 10000) {
								
								 JSONObject jsonObject= object.optJSONObject("data")
										.optJSONObject("schedule");
                               if(jsonObject!=null){
                            	   String rdtime=jsonObject.optString("rdtime");
								tempData = (List<DoctorOrderSchedule>) JsonUtil
										.parseJsonToList(
												rdtime,
												new TypeToken<List<DoctorOrderSchedule>>() {
												}.getType());
								
								System.out.println("获取的size的值 是 多少呢 .."+tempData.size());
//								msg.what = DOCTORSCHEDULSUCESS;
//								handler.sendMessage(msg);
								
								//改变返回的数据结构
								trunle();
                               }

							} else {
								UIUtil.showToast(context, Msg);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				});
		getRequest.setIsParseJson(false);
		executeRequest(getRequest);
	}

	
	public void trunle(){
		Set<String> set = new HashSet<String>();
		for(int i=0;i<tempData.size();i++){
		    set.add(tempData.get(i).getDate());
		}
		System.out.println(set.size());
		List<DoctorOrderSchedule> list = new ArrayList<DoctorOrderSchedule>();
		Iterator<String> iter = set.iterator();
		DoctorOrderSchedule current_doctor = null;
		while(iter.hasNext()){
			String current_str = iter.next();
			int count = 0;
			for(int k=0;k<tempData.size();k++){
				DoctorOrderSchedule temp = tempData.get(k);
				if(temp.getDate().equals(current_str)){
					list.add(tempData.get(k));
					count++;
					current_doctor = tempData.get(k);
				}
			}
			if(count ==1){
				String noon = current_doctor.getHalfday();
				DoctorOrderSchedule bean0 = new DoctorOrderSchedule();
				bean0.setDate(current_doctor.getDate());
				bean0.setId("-1");
				DoctorOrderSchedule bean1 = new DoctorOrderSchedule();
				bean1.setDate("11");
				bean1.setId("-2");
				if(noon.equals("1")){
					bean1.setHalfday("2");
					list.add(bean1);
				}else {
					bean1.setHalfday("1");
					list.add(list.size()-1,bean1);
				}
				list.add(list.size()-2,bean0);
			}else if (count==2) {
				DoctorOrderSchedule bean0 = new DoctorOrderSchedule();
				bean0.setDate(current_doctor.getDate());
				bean0.setId("-1");
				int size = list.size()-2;
				list.add(size,bean0);
			}
		}
		
		GridAdapter adapter = new GridAdapter(list, this);
		mygridview.setAdapter(adapter);
	}
	/**
	 * 设置表格的字
	 * 
	 * @param view
	 * @param text
	 */
	private void setText(TextView view, String text) {
		view.setText(text);
	}

	private String changtype(String type) {

		// 门诊类型 (1:普通 2：专家 3：特需 4：专科 5：会诊 6：夜间)

		if (map == null) {
			map = new HashMap<Integer, String>();
			map.put(1, "普通");
			map.put(2, "专家");
			map.put(3, "特需");
			map.put(4, "专科");
			map.put(5, "会诊");
			map.put(6, "夜间");
		}
		Iterator it = map.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			Integer key = (Integer) entry.getKey();
			String value = (String) entry.getValue();
			if (Integer.valueOf(type) == key) {
				return value;
			}
		}
		return "";

	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.left_img:
			finish();
			break;

		default:
			break;
		}
	}
	
	private  void setBackGround(TextView  view){
		view.setBackgroundResource(R.color.schedule_color);
	}

	public Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {

			case DOCTORSCHEDULSUCESS:{

				}

				break;

			default:
				break;
			}
		}
	};
	
	class GridAdapter extends BaseAdapter{
       private List<DoctorOrderSchedule> list;
       private Context context;
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return this.list.size();
		}

		public GridAdapter(List<DoctorOrderSchedule> list, Context context) {
			super();
			this.list = list;
			this.context = context;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			final DoctorOrderSchedule bean = this.list.get(position);
			
			viewHolder holder;
			Calendar calendar = Calendar.getInstance();
			calendar.setTimeInMillis(Long.valueOf(bean.getDate())*1000);
			if(convertView==null){
				holder=new viewHolder();
				convertView=View.inflate(context, R.layout.item_order_doctor, null);
				
				holder.order_tv1=(TextView) convertView.findViewById(R.id.order_tv1);
//				holder.order_tv2=(TextView) convertView.findViewById(R.id.order_tv2);
//				holder.order_tv3=(TextView) convertView.findViewById(R.id.order_tv3);
				convertView.setTag(holder);
			}else{
				holder=(viewHolder) convertView.getTag();
			}
			if(bean.getId().equals("-1")){
				String date = DateUtil.getMouthAndDays(bean.getDate());
				int week = calendar.get(Calendar.DAY_OF_WEEK)-1;
				String week_str = "";
				if(week == 0){
					week_str = weekStr[6];
				}else {
					week_str = weekStr[week-1];
				}
				holder.order_tv1.setText(date+"\n"+week_str);
			}else if (bean.getId().equals("-2")) {
				holder.order_tv1.setText("");
			}else {
				if(Integer.valueOf(bean.getSurplus())>0){
					holder.order_tv1.setText(bean.getMsg()+"\n"+"(剩余"+bean.getSurplus()+"个)");
				}else{
					holder.order_tv1.setText("已预约完");
				}
			}
//			if(Integer.valueOf(bean.getSurplus())>0&&!bean.getId().equals("-1")&&!bean.getId().equals("-2")){
				convertView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if(!bean.getId().equals("-1")&&!bean.getId().equals("-2")){
						Bundle bundle=new Bundle();
						bundle.putString("doctor_id", doc_id);
						bundle.putString("expert_id",expertid);//
						bundle.putString("id",bean.getId());//
						bundle.putString("date", bean.getDate());
						if(User.getInstance(context).getUserid().length()>0)
						enterActivity(PlusInfoOneAct.class,bundle);
						else{
							UIUtil.showToast(context, "请先登录");
							enterActivity(LoginAct.class);
						}
						}
					}
				});
//			}
			return convertView;
		}
		
		  private class viewHolder{
			  private  TextView order_tv1;
		   }
		
	}
	
	String weekStr[] = {
			"周一",
			"周二",
			"周三",
			"周四",
			"周五",
			"周六",
			"周日"
	};
	private String document;
}
